<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <el-button
              type="primary"
              size="small"
              @click="showDialog = true"
            >+ 新增角色</el-button>
            <el-table style="margin: 10px 0" :data="list">
              <el-table-column
                label="序号"
                width="80"
                type="index"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="150" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button
                    type="success"
                    size="small"
                    @click="clickShowAssignDialog(row.id)"
                  >分配权限</el-button>
                  <el-button
                    type="primary"
                    size="small"
                    @click="edit(row.id)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="del(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4, 5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
        <el-form ref="form" label-width="100px" :model="form" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="clickSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限弹窗 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
      >
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          :data="permissionList"
          :props="{ label: 'name' }"
          show-checkbox
          check-strictly
          default-expand-all
          node-key="id"
        />
        <template #footer>
          <div style="text-align: reight">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssignSubmit">确认</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  reqGetRoleList,
  reqDelRole,
  reqAddRole,
  reqGetRoleDetail,
  reqUpdateRole
} from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { mapState } from 'vuex'
import { reqGetPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils/index'
import { reqAssignPermission } from '@/api/setting'
export default {
  name: 'Setting',
  data() {
    return {
      showAssignDialog: false,
      treeLoading: false,
      activeName: 'role',
      list: [],
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '角色名称不能为空',
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            required: true,
            message: '角色描述不能为空',
            trigger: ['blur', 'change']
          }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      page: 1,
      pagesize: 2,
      total: 0,
      loading: false,
      showDialog: false,
      permissionList: [],
      roleId: ''
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },

  created() {
    this.getRoleList()
    this.getCompanyById()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const {
        data: { rows, total }
      } = await reqGetRoleList(this.page, this.pagesize)
      this.list = rows
      this.total = total

      this.loading = false
    },
    handleSizeChange(val) {
      // console.log(val)
      this.pagesize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // console.log(val)
      this.page = val
      this.getRoleList()
    },
    indexMethod(index) {
      return index + 1 + this.pagesize * (this.page - 1)
    },
    del(id) {
      this.$confirm('确定删除该角色么?', '温馨提示')
        .then(async() => {
          await reqDelRole(id)
          this.$message.success('删除角色成功')
          if (this.page > 1 && this.list.length === 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    closeDialog() {
      this.showDialog = false
      this.$refs.form.resetFields()
      this.form = { name: '', description: '' }
    },
    clickSubmit() {
      this.$refs.form.validate(async(flag) => {
        if (!flag) return

        if (this.form.id) {
          await reqUpdateRole(this.form)
          this.$message.success('更新角色成功')
        } else {
          await reqAddRole(this.form)
          this.$message.success('新增角色成功')
        }
        this.showDialog = false
        this.getRoleList()
      })
    },
    async edit(id) {
      this.showDialog = true

      const { data } = await reqGetRoleDetail(id)
      this.form = data
    },
    async getCompanyById() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    async clickShowAssignDialog(id) {
      this.treeLoading = true
      this.showAssignDialog = true
      // console.log(id)
      const { data } = await reqGetPermissionList()
      this.permissionList = transListToTree(data, '0')
      // console.log(this.permissionList)
      const {
        data: { permIds }
      } = await reqGetRoleDetail(id)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
      this.roleId = id
      this.treeLoading = false
    },
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async clickAssignSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log(permIds)
      await reqAssignPermission(this.roleId, permIds)
      // console.log(res)
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    }
  }
}
</script>

<style>
</style>
